#ifndef __SC_INTERNAL_H
#define __SC_INTERNAL_H
#include "uthash.h"

#ifdef __cplusplus
extern "C"
{
#endif


/* 订阅信息结构体 */
typedef struct sc_context{
    const char* id;
    void (*onwrite)(const char* sourceid,void *msg,int len, char* topic);
}sc_context;

typedef struct sc_msg{
    char* msg;
    int len;
}sc_msg;

/* 叶子节点的订阅队列 */
typedef struct sc_subleaf{
    struct sc_subleaf *prev;
    struct sc_subleaf *next;
    struct sc_context  * context;
}sc_subleaf;

typedef struct sc_subhier {
    UT_hash_handle hh;
    struct sc_subhier* parent;      /* 父节点 */
    struct sc_subhier* children;    /* 孩子节点 */
    struct sc_subleaf* subs;       /* 订阅链表头 */
    char* topic;                    /* 当前节点名称 */
    int topic_len;         //    /* 当前节点名称长度 */ 
}sc_subhier;



/* 对saveptr 进行切割，返回第一个字段
例如：b/1/24/5 返回b ,多次调用，可以依次返回字段
*/
char *strtok_hier(char *str, char **saveptr);

/*
fun: 将url 切割成独立的数组
subtopic: 订阅url a/b/c
local_sub: 临时变量
topics: 输出的topic 数组
sharename: 暂时无用
*/
int sub_topic_tokenise(const char *subtopic, char **local_sub, char ***topics, const char **sharename);


/* 内部调用函数 */
int sub__add(struct sc_context* context, const char* sub, int options, struct sc_subhier** root);

struct sc_subhier* sub_add_heir_entry(struct sc_subhier* parent, struct sc_subhier** sibling, const char* topic, uint16_t len);

static int sub_add_context(struct sc_context* context, const char* topic_filter, int options, struct sc_subhier* subhier, char* const* const topics, const char* sharename);

static int sub_add_leaf(struct sc_context* context, int options, struct sc_subleaf** head, struct sc_subleaf** newleaf);

// 消息发送
int sub__messages_queue(const char* source_id, const char* topic, struct sc_msg* msg);

int sub_search(struct sc_subhier* sub, char** split_topics, const char* sourceid, const char* topic, struct sc_msg* msg);


static int sub_process(struct sc_subhier* hier, const char* source_id, const char* topic, struct sc_msg* msg);
static int subs__send(const char* source_id, struct sc_subleaf* leaf, const char* topic, struct sc_msg* msg);



#ifdef __cplusplus
}
#endif

#endif
